//
//  QXPhotoViewerVC.swift
//  QXWeibo
//
//  Created by QinXin on 15/7/3.
//  Copyright © 2015年 labi3285_Lab. All rights reserved.
//

import UIKit
import FFAutoLayout
import SVProgressHUD

class QXPhotoViewerVC: UIViewController, UICollectionViewDataSource {
    
    private var imageURLs: [NSURL]
    private var index: Int
    
    lazy private var flowLayout = UICollectionViewFlowLayout()
    lazy private var collectionView: UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: self.flowLayout)

    init(urls: [NSURL], idx: Int) {
        
        imageURLs = urls
        index = idx
        
        super.init(nibName: nil, bundle: nil)
        
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = UIColor.blackColor()
        view.addSubview(collectionView)
        
        collectionView.pagingEnabled = true
        collectionView.dataSource = self
        collectionView.registerClass(QXPhotoViewerCollectionCell.self, forCellWithReuseIdentifier: "QXPhotoViewerCollectionCell")
        
        collectionView.ff_AlignInner(ff_AlignType.CenterCenter, referView: view, size: CGSize(width: UIScreen.mainScreen().bounds.width + 20.0, height: UIScreen.mainScreen().bounds.height))
        
        let long = UILongPressGestureRecognizer(target: self, action: "popMenu:")
        view.addGestureRecognizer(long)
        let tap = UITapGestureRecognizer(target: self, action: "close")
        view.addGestureRecognizer(tap)
    }

    // 在这个方法里才能保证 collectionView 的frame已经确定
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        
        flowLayout.itemSize = collectionView.bounds.size
        flowLayout.minimumInteritemSpacing = 0
        flowLayout.minimumLineSpacing = 0
        flowLayout.scrollDirection = UICollectionViewScrollDirection.Horizontal
        
        let idxpath = NSIndexPath(forRow: self.index, inSection: 0)
        collectionView.scrollToItemAtIndexPath(idxpath, atScrollPosition: UICollectionViewScrollPosition.CenteredHorizontally, animated: false)
        
    }
    
    func popMenu(recognizer: UILongPressGestureRecognizer) {
        //解决响应两次的问题
        if (recognizer.state == UIGestureRecognizerState.Ended) {
            return;
        } else if (recognizer.state == UIGestureRecognizerState.Began) {
            let sheet = UIActionSheet(title: "菜单", delegate: self, cancelButtonTitle: "取消", destructiveButtonTitle: "保存")
            sheet.showInView(view)
        }
    }
    
    func save() {
        let idxPath = collectionView.indexPathsForVisibleItems().last!
        let cell = collectionView.cellForItemAtIndexPath(idxPath) as! QXPhotoViewerCollectionCell
        let image = cell.imageView.image
        UIImageWriteToSavedPhotosAlbum(image!, self, "image:didFinishSavingWithError:contextInfo:", nil)
    }
    
    func close() {
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    func image(image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: AnyObject) {
        if error != nil {
            SVProgressHUD.showErrorWithStatus("保存失败！")
        } else {
            SVProgressHUD.showSuccessWithStatus("保存成功！")
        }
    }
    
    /// 返回当前的图片的绝对frame
    func getCurrentImageViewAbsoluteFrame() -> CGRect {
        let idxPath = collectionView.indexPathsForVisibleItems().last!
        let cell = collectionView.cellForItemAtIndexPath(idxPath) as! QXPhotoViewerCollectionCell
        return CGRect(x: -cell.scrollView.contentOffset.x, y: -cell.scrollView.contentOffset.y, width: cell.imageView.frame.size.width, height: cell.imageView.frame.size.height)
    }
    
    /// 返回当前的图片框
    func getCurrentImageView() -> UIImageView {
        let idxPath = collectionView.indexPathsForVisibleItems().last!
        let cell = collectionView.cellForItemAtIndexPath(idxPath) as! QXPhotoViewerCollectionCell
        return cell.imageView
    }
    
    /// 返回当前的索引
    func getCurrentImageIdx() -> Int {
        return collectionView.indexPathsForVisibleItems().last!.item
    }
    
    
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {        
        return imageURLs.count
    }

    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("QXPhotoViewerCollectionCell", forIndexPath: indexPath) as! QXPhotoViewerCollectionCell
        cell.imageURL = self.imageURLs[indexPath.item]
        return cell
    }
    
}

extension QXPhotoViewerVC: UIActionSheetDelegate {
    func actionSheet(actionSheet: UIActionSheet, clickedButtonAtIndex buttonIndex: Int) {
        if buttonIndex == 0 {
            save()
        }
    }
}
